package com.adopapa.nezhacloud.authc.codegen;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.adopapa.nezhacloud.authc.controller.DepartmentInfoController;
import com.adopapa.nezhacloud.authc.controller.PermissionController;
import com.adopapa.nezhacloud.authc.controller.ResourceInfoController;
import com.adopapa.nezhacloud.authc.controller.RoleInfoController;
import com.adopapa.nezhacloud.authc.controller.UserInfoController;
import com.adopapa.nezhacloud.authc.domain.ResourceInfo.ResourceType;
import com.adopapa.nezhacloud.authc.domain.UserInfo;
import com.adopapa.nezhacloud.common.Tools;
import com.adopapa.nezhacloud.common.UuidUtils;
import com.adopapa.nezhacloud.ddd.codegen.SqlGen;

public class GenSqlMain {

	public final static String INSERT_SQL_TEMPLATE = "INSERT INTO AUTHC_RESOURCE(ID, RESOURCE_NAME, "
			+ "RESOURCE_URL, RESOURCE_TYPE, REMARK) VALUES ('%s', '%s', '%s', '%s', '%s');";

	public static void main(String[] args) {
		generateSqls(UserInfoController.class);
		generateSqls(RoleInfoController.class);
		generateSqls(ResourceInfoController.class);
		generateSqls(PermissionController.class);
		generateSqls(DepartmentInfoController.class);

//		generateSql(UserInfo.class);
	}

	public static String generateSql(Class<?> clazz) {
		List<Field> fields = getFields(clazz);
		for (Field field : fields) {
			System.err.println(field.getName());
		}

		return null;
	}

	public static List<Field> getFields(Class<?> clazz) {
		List<Field> fields = new LinkedList<Field>();
		Class<?> superclazz = clazz.getSuperclass();
		if (superclazz != null) {
			fields.addAll(getFields(clazz.getSuperclass()));
		}
		for (Field field : clazz.getDeclaredFields()) {
			if (!field.getName().equals("serialVersionUID")) {
				fields.add(field);
			}
		}
		
		return fields;
	}

	public static List<String> generateSqls(Class<?> clazz) {
		List<String> sqls = new LinkedList<String>();

		RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
		String path = requestMapping.value()[0];

		String sql = null;
		Method[] methods = clazz.getDeclaredMethods();
		for (Method method : methods) {
			SqlGen sqlGen = method.getAnnotation(SqlGen.class);
			if (!Tools.empty(sqlGen)) {
				sql = String.format(INSERT_SQL_TEMPLATE, UuidUtils.fastSimpleUUID(), //
						StringUtils.join(sqlGen.name(), ","), path.concat(sqlGen.path()[0]), //
						ResourceType.MENU.ordinal(), "");
				System.out.println(sql);
				sqls.add(sql);
			}
		}

		return sqls;

	}

}
